import json
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Callable
from datetime import datetime

import pandas as pd
from plugin.telnet import run_t
from plugin.ssh import run_s

POOL: int = 50
DATETIME: str = datetime.now().strftime("%Y-%m-%d %H.%M.%S")
DATE: str = datetime.now().strftime("%Y-%m-%d")
BASEDIR: Path = Path(__file__).resolve().parent.parent

CFG_PATH: str = f"config/{DATE}"
ERROR_FILE: str = "error.log"


# 从excel中获取设备
def get_device() -> list[dict]:
    df = pd.read_excel(BASEDIR.joinpath("交接清单.xlsx"), sheet_name="脚本")
    return df.to_dict('records')


# 对线程池的一个简单处理默认支持50个并发
def start_thread(fn: Callable, data: list) -> list:
    with ThreadPoolExecutor(max_workers=POOL) as pool:
        result = as_completed([pool.submit(fn, **item) for item in data])
        response = [i.result() for i in result]
        return response


# 对线程池的一个简单处理默认支持50个并发,同时支持telnet和ssh
def start_ts_thread(data: list) -> list:
    with ThreadPoolExecutor(max_workers=POOL) as pool:
        task: list = []
        for item in data:
            if item['login'] == 'ssh':
                task.append(pool.submit(run_s, **item))
            else:
                task.append(pool.submit(run_t, **item))
        result = as_completed(task)
        response = [i.result() for i in result]
        return response


# 创建目录
def create_path(path: str):
    BASEDIR.joinpath(path).mkdir(parents=True, exist_ok=True)


# 保存配置
def save_configure(data: dict):
    create_path(CFG_PATH)
    title: str = f"{data.get('device')} {data.get('host')} {data.get('hostname')} {DATETIME}.vrp"
    cfg: Path = BASEDIR / CFG_PATH / title
    with cfg.open(mode="w+") as f:
        f.write(data.get('data'))


# 保存错误
def save_error(data: dict):
    err: Path = Path(ERROR_FILE)
    data['date'] = DATETIME
    with err.open("a+") as e:
        e.write(json.dumps(data) + "\n")


if __name__ == '__main__':
    print(DATETIME)
    print(DATE)
    print(BASEDIR)
    save_configure({})
    # with open("1.txt", mode='w+') as f:
    #     f.write("1111")
